/**
 * Created by chenweicheng on 19/6/18.
 */
/**
 * Created by chenweicheng on 15/7/17.
 */
import React, {PureComponent} from 'react'
import {
    View,
    Text,
    StyleSheet,
    Image,
    TouchableOpacity,
    NativeAppEventEmitter,
    Platform,
    Alert,
    TextInput,
    ScrollView
} from 'react-native'

import {NavigationActions} from 'react-navigation'
import {px2dpH, px2dpW} from '../config/px2dp'
import theme from '../config/theme'
import ModalDialog from '../widget/ModalDialog'
import ModalListDialog from '../widget/ModalListDialog'
import  ProtobufJsManager from "../proto/ProtobufJsManager"
import net from 'net';

import  UtilManager from "../util/UtilManager"
import  TcpManager from "../manager/TcpManager"
import  MsgManager from "../manager/MsgManager"
export  default class SettingScene extends PureComponent {
    static navigationOptions = ({navigation}) => ({

        headerTitle: '获取数据',

        headerRight: <View/>,
        headerStyle: theme.headerStyle,


    });


    constructor() {
        super();

        this.state = {
            reload: false
        }
        this.ssid = "";
        this.wifipswd = "";

        this.ip = ""
        this.port = "";
        this.chatter = [];
        this.updateChatter = this.updateChatter.bind(this);

        this.tcpsend = ""
    }

    reload() {
        this.setState({reload: !this.state.reload})
    }


    componentWillMount() {


    }

    updateChatter(msg) {

        this.chatter = this.chatter.concat([msg])
        this.reload()

    }

    sub() {
        this._fousListener = this.props.navigation.addListener('didFocus', () => {
            console.log("_fousListener")
        });
        this._blurListener = this.props.navigation.addListener('willBlur', () => {
            console.log("_blurListener")
        });
    }

    unsub() {
        this._fousListener.remove();
        this._blurListener.remove();
    }

    componentDidMount() {

        this.sub()


        UtilManager.getWifiConnectedSsid().then((data) => {
            console.log("success", data)
            this.ssid = data
            this.reload()
        }, (error) => {
            this.ssid = '';
            console.log("fail", error)
        })


    }

    SnapConfig() {
        // if (this.ssid != "" && this.wifipswd != "") {
        //
        //     let SnapMsg = ProtobufJsManager.getProtoMessage(ProtobufJsManager.headerType.SnapApp);
        //     //根据实际情况set
        //     let snapconfig = {SSID: this.ssid, password: this.wifipswd}
        //
        //     let loopcount = ProtobufJsManager.getLoopCount();
        //
        //     let data = {
        //         loopCount: loopcount,
        //         timestamp: new Date().getTime() + "",
        //         type: 4,
        //         config: snapconfig
        //     };
        //
        //
        //     console.log('SnapConfig DATA', data);
        //     let message = SnapMsg.create(data);
        //
        //
        //     //生成一个SnapMsg消息
        //     ProtobufJsManager.createMessage(message, ProtobufJsManager.headerType.SnapApp).then((createMsg) => {
        //         //生成的消息
        //         console.log("create message success:" + createMsg);
        //
        //         // ProtobufJsManager.parseMessage(createMsg, ProtobufJsManager.headerType.SnapApp).then((result) => {
        //         //     console.log('GET DATA RESULT FROM DEVICE', result);
        //         // }, (error) => {
        //         //     console.log("error=" + error)
        //         // });
        //         this.tcpsend = createMsg
        //         this.reload()
        //
        //     }, (error) => {
        //         console.log("create message fail:" + error)
        //     });
        // } else {
        //     alert("wifi or pswd blank")
        // }

        MsgManager.SnapConfig(this.ssid, this.wifipswd).then((result) => {
            this.tcpsend = result.msg
            this.reload()
            console.log(result.loopcount, result.msg)
        }, (fail) => {
            alert(fail)
        })

    }

    clientConnect() {
        console.log(this.ip, this.port)
        // let client = net.createConnection({host: this.ip, port: this.port}, () => {
        //     this.updateChatter('opened client on ' + JSON.stringify(client.address()));
        //   //  client.write('Hello, server! Love, Client.');
        //     this.tcpready=true;
        // });
     //   let client = TcpManager.clientConnect(this.ip, this.port)
        TcpManager.clientConnect(this.ip, this.port).then((client) => {
            this.client = client
        }, (error) => {
            console.log("client tcp error", error)
        })
        //TcpManager.client.on('data', this.ondata.bind(this));

        // this.client.destroy(); // kill client after server's response
        // this.server.close();
        // TcpManager.client.on('error', (error) => {
        //     this.updateChatter('client error ' + error);
        //     //this.tcpready = false
        // });
        //
        // TcpManager.client.on('close', () => {
        //     this.updateChatter('client close');
        //     //this.tcpready = false
        // });

        //   this.client = client;
    }

    ondata(zz) {

        console.log("Getdatascene  Received:", zz)
        this.updateChatter('Getdatascene  Received: ' + zz);
    }

    send() {
        TcpManager.client.write(this.tcpsend);
    }

    componentWillUnmount() {
        this.unsub()
        //TcpManager.clientDisconect()
    }

    onchangeip(text) {
        this.ip = text + ""
        //  console.log("onchangeip", this.ip)


    }

    onchangeport(text) {
        this.port = text
        //console.log("onchangeip", this.port)

    }

    onchangewifipswd(text) {
        this.wifipswd = text
        //console.log("onchangewifipswd", this.wifipswd)

    }

    ontcpsend(text) {
        this.tcpsend = text
        // console.log("ontcpsend", this.tcpsend)

    }

    testtest() {

        ProtobufJsManager.parseMessage("08011006328a010a0a159a99993f1d9a9919400a0c0801159a99993f1d9a9919400a0c0802159a99993f1d9a9919400a0c0803159a99993f1d9a9919400a0c0804159a99993f1d9a9919400a0c0805159a99993f1d9a9919400a0c0806159a99993f1d9a9919400a0c0807159a99993f1d9a9919400a0c0808159a99993f1d9a9919400a0c0809159a99993f1d9a991940".replace(" ", ""), ProtobufJsManager.headerType.SnapDevice).then((result) => {
            console.log('GET DATA RESULT FROM DEVICE', result);
        }, (error) => {
            console.log("error=" + error)
        });
    }

    render() {

        return (
            <View style={styles.container}>

                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    editable={false}
                    defaultValue={this.ssid}
                    underlineColorAndroid={"transparent"}
                    placeholder={"wifi"}
                />
                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={this.onchangewifipswd.bind(this)}
                    defaultValue={this.wifipswd}
                    underlineColorAndroid={"transparent"}
                    placeholder={"wifi password"}
                />
                <Text onPress={this.SnapConfig.bind(this)} style={{fontSize:20}}>生成配置消息</Text>
                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={this.onchangeip.bind(this)}
                    defaultValue={this.ip}
                    underlineColorAndroid={"transparent"}
                    placeholder={"ip"}
                />
                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={this.onchangeport.bind(this)}
                    defaultValue={this.port}
                    underlineColorAndroid={"transparent"}
                    placeholder={"port"}
                />
                <TouchableOpacity onPress={this.clientConnect.bind(this)}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text> connect client</Text>
                </TouchableOpacity>


                <TextInput
                    style={{width:px2dpW(240),height: 40, borderColor: 'gray', borderWidth: 1}}
                    onChangeText={this.ontcpsend.bind(this)}
                    defaultValue={this.tcpsend}
                    underlineColorAndroid={"transparent"}
                    placeholder={"tcpsend"}
                />
                <TouchableOpacity onPress={this.send.bind(this)}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text> send cmd</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={()=>this.props.navigation.navigate("TestTcp")}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text> 跳转到下一测试页面</Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.testtest.bind(this)}
                                  style={{height:50,width:120,backgroundColor:'#eeeeee',alignItems:'center',justifyContent:'center',margin:5}}>
                    <Text> TESTTEST</Text>
                </TouchableOpacity>
                <ScrollView>
                    {this.chatter.map((msg, index) => {
                        return (
                            <Text key={index}>
                                {msg}
                            </Text>
                        );
                    })}
                </ScrollView>

            </View>)
    }
}


const
    styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: 'white',
            alignItems: 'center'

        }


    });
